package com.kun.portal.webframe.controller;


import com.kun.portal.webframe.po.DeptMgrPo;

import com.kun.portal.webframe.service.DeptMgrService;

import com.kun.portal.webframe.util.HeaderUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by Administrator on 2018/5/21.
 */
@Controller
@RequestMapping({"/api/deptMgr"})
public class DeptMgrController {
    @Autowired
    private DeptMgrService deptMgrService;

    @RequestMapping(
            value = {"/subDept"},
            method = {RequestMethod.GET}
    )
    @ResponseBody
    public List<DeptMgrPo> findByParentCode(@RequestParam(value = "parentCode",required = false) String parentCode){

        return deptMgrService.findByParentCode(parentCode);
    }
   @RequestMapping(
            value = {"/addDept"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public ResponseEntity<DeptMgrPo> addDept(@RequestBody DeptMgrPo dept) {
        DeptMgrPo deptMgrPo = this.deptMgrService.addDept(dept);
        return new ResponseEntity(deptMgrPo, HttpStatus.OK);
    }
    @RequestMapping(
            value = {"/updateDept"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
        public ResponseEntity<DeptMgrPo> updateDept(@RequestBody DeptMgrPo deptMgr, HttpSession session) {

            String deptCode = deptMgr.getDeptCode();
            if(deptCode.equals("")) {
                String parentCode = deptMgr.getParentCode();
                int deptCodeLen = parentCode == null?2:parentCode.length() + 2;
                String maxDeptCode = this.deptMgrService.findMaxDeptCodeByParentCode(parentCode);
                deptCode = maxDeptCode == null?"1":String.valueOf(Long.valueOf(maxDeptCode).longValue() + 1L);
                deptCode = deptCode.length() < deptCodeLen?"0" + deptCode:deptCode;
                if(parentCode != null && deptCode.length() <= parentCode.length()) {
                    deptCode = parentCode + deptCode;
                }

                deptMgr.setDeptCode(deptCode);
            }
            DeptMgrPo deptMgrPo = this.deptMgrService.updateDept(deptMgr);
            return new ResponseEntity(deptMgrPo, HttpStatus.OK);
        }
    @RequestMapping(
            value = {"/deleteDept/{deptId}"},
            method = {RequestMethod.DELETE}
    )
    @ResponseBody
    public ResponseEntity<Void> deleteFwModule(@PathVariable("deptId") String deptId) {
        this.deptMgrService.deleteDeptMgr(deptId);
        return ((ResponseEntity.BodyBuilder)ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("deptMgrPo", deptId))).build();
    }







}
